﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
namespace DataSyn.Forms
{
    public partial class FormMain1 : DataSyn.Forms.FormBase
    {
        private void LoadProject()
        {
            var projects = MDL.CPublic.dc.TProject.ToList();
            tProjectBindingSource.DataSource = projects;
            foreach (var project in projects)
                if (project.IsRunning)
                    project.sync.StartSync();
        }
        public FormMain1()
        {
            InitializeComponent();
        }
        private void FormMain1_Load(object sender, EventArgs e)
        {
            tDataTableBindingSource.DataSource = new List<DAL.DB.Tables.TDataTable>();
            if (string.IsNullOrWhiteSpace(MDL.CPublic.config.DataConnectionString))
            {
                using (BaseLibrary.UControls.DBSetting.Form_Setting form = new BaseLibrary.UControls.DBSetting.Form_Setting() {  Provider= BaseLibrary.CDataContext.EProvider.SQLite})
                {
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        MDL.CPublic.config.DataConnectionString = form.Connection;
                        MDL.CPublic.config.Provider = form.Provider;
                        MDL.CPublic.config.Save();
                    }
                    else
                    {
                        this.Close();
                        return;
                    }
                }
            }
            MDL.CPublic.dc = new DAL.DB.DataContext(MDL.CPublic.config.Provider, MDL.CPublic.config.DataConnectionString);
            MDL.CPublic.dc.CheckAllSchema();
            LoadProject();
        }

        private void barButtonItem_ManagerConnection_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (Forms.FormConnectionSetting form = new FormConnectionSetting())
                form.ShowDialog();
        }

        private void barButtonItem_Project_Add_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var tem = new DAL.DB.Tables.TProject();
            MDL.CPublic.dc.Save(tem);
            tProjectBindingSource.Add(tem);
        }

        private void gridView_Project_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            var tem = tProjectBindingSource.Current as DAL.DB.Tables.TProject;
            if (tem == null) return;
            if (e.Column == colProjectName)
                tem.ProjectName = string.Format("{0}", e.Value);
            else if (e.Column == colIsTwoWay)
                tem.IsTowWay = BaseLibrary.ClassLibrary.DataConver.ToBool(e.Value);
            else if (e.Column == colIsRunning)
                tem.IsRunning = BaseLibrary.ClassLibrary.DataConver.ToBool(e.Value);
            MDL.CPublic.dc.Save(tem);
            if (tem.IsRunning)
                tem.sync.StartSync();
            else
                tem.sync.StopSync();
        }
        private void repositoryItemButtonEdit_Project_Delete_Click(object sender, EventArgs e)
        {
           
        }

        private void repositoryItemButtonEdit_Project_Delete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var tem = tProjectBindingSource.Current as DAL.DB.Tables.TProject;
            if (tem == null) return;
            tem.Delete();
            MDL.CPublic.dc.Save(tem);
            tProjectBindingSource.Remove(tem);
        }

        private void barButtonItem_DataBase_Add_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var project = tProjectBindingSource.Current as DAL.DB.Tables.TProject;
            if (project == null) return;
            var tem = new DAL.DB.Tables.TDataBase() { ProjectID = project.ID };
            tDataBaseBindingSource.Add(tem);
        }

        private void tProjectBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            var project = tProjectBindingSource.Current as DAL.DB.Tables.TProject;
            if (project == null) return;
            tDataBaseBindingSource.DataSource = MDL.CPublic.dc.TDataBase.Where(c => c.ProjectID == project.ID).ToList();
            ReadDataTable(project.ID);
        }

        private void gridView_DataBase_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column == colConnectionID)
            {
                var id =  BaseLibrary.ClassLibrary.DataConver.ToInt(e.CellValue);
                var tem = MDL.CPublic.dc.TConnection.FirstOrDefault(c => c.ID == id);
                if (tem == null)
                    e.DisplayText = "";
                else
                {
                    e.DisplayText = string.Format("{0}", tem.ConnectionName);
                }
            }
        }
        private void gridView_DataBase_ShowingEditor(object sender, CancelEventArgs e)
        {
            if (gridView_DataBase.FocusedColumn == colDataBase)
            {
                repositoryItemComboBox_DataBase.Items.Clear();
                try
                {
                    var database = tDataBaseBindingSource.Current as DAL.DB.Tables.TDataBase;
                    if (database == null) return;
                    var conn = MDL.CPublic.dc.TConnection.FirstOrDefault(c => c.ID == database.ConnectionID);
                    if (conn == null) return;
                    using (BaseLibrary.CDataContext.DataContext dc = new BaseLibrary.CDataContext.DataContext(conn.Provider, conn.ConnectionString))
                    {
                        repositoryItemComboBox_DataBase.Items.AddRange(dc.GetList<string>("select name from sysdatabases where name not in ('master','msdb','tempdb','model') order by name").ToArray());
                    }
                }
                catch (Exception ex)
                { }
            }
            else if (gridView_DataBase.FocusedColumn == colConnectionID)
            {
                repositoryItemComboBox_Conn.Items.Clear();
                repositoryItemComboBox_Conn.Items.AddRange(MDL.CPublic.dc.TConnection.ToList().Select(c => c.ConnectionName).ToArray());
            }
        }

        private void gridView_DataBase_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            var project = tProjectBindingSource.Current as DAL.DB.Tables.TProject;
            if (project == null) return;
            var database = tDataBaseBindingSource.Current as DAL.DB.Tables.TDataBase;
            if (database == null) return;
            if (gridView_DataBase.FocusedColumn == colIsMasterDB)
            {
                if (BaseLibrary.ClassLibrary.DataConver.ToBool(e.Value))
                {
                    var List = tDataBaseBindingSource.DataSource as List<DAL.DB.Tables.TDataBase>;
                    if (List != null && List.Count > 0)
                        foreach (var row in List.Where(c => c.ID != database.ID))
                        {
                            row.IsMasterDB = false;
                            MDL.CPublic.dc.Save(row);
                        }
                    gridView_DataBase.RefreshData();
                }
            }
            else if (gridView_DataBase.FocusedColumn == colDataBase )
            {
                database.DataBase = string.Format("{0}", e.Value);
                if(!string.IsNullOrWhiteSpace(database.DataBase))
                MDL.CPublic.dc.Save(database);
            }
            ReadDataTable(project.ID);
        }
        private void gridView_DataBase_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            var database = tDataBaseBindingSource.Current as DAL.DB.Tables.TDataBase;
            if (database == null || string.IsNullOrWhiteSpace(database.DataBase)) return;
            MDL.CPublic.dc.Save(database);
        }
        private void repositoryItemComboBox_Conn_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
           e.NewValue = MDL.CPublic.dc.TConnection.Where(c => c.ConnectionName == string.Format("{0}", e.NewValue)).ToList().Select(c => c.ID).FirstOrDefault();
        }
        private void ReadDataTable(int projectID)
        {
            try
            {
                tDataTableBindingSource.Clear();
                if (projectID == 0) return;
                var masterDataBase = MDL.CPublic.dc.TDataBase.FirstOrDefault(c => c.ProjectID == projectID);
                if (masterDataBase == null) return;
                var dc = MDL.CPublic.dc.GetDataBaseDC(masterDataBase.ID);
                if (dc == null) return;
                gridView_DataTable.CellValueChanging -=gridView_DataTable_CellValueChanging;
                foreach (var table in dc.GetTables().Where(c => c.SchemaName != MDL.Sync.syncSchema).OrderBy(c => c.TableName))
                {
                    tDataTableBindingSource.Add(new DAL.DB.Tables.TDataTable() { ProjectID = projectID, TableName = table.TableName, IsSync = (MDL.CPublic.dc.TDataTable.Count(c => c.ProjectID == projectID && c.TableName == table.TableName) > 0) });
                }
                gridView_DataTable.CellValueChanging += gridView_DataTable_CellValueChanging;
            }
            catch (Exception ex)
            {
                MDL.CPublic.log.Write(string.Format("项目{0}读取主库表名列表时异常：{1}",projectID, ex.Message));
                MDL.CPublic.log.Write(ex);
            }
        }


        private void gridView_DataTable_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (gridView_DataTable.FocusedColumn == colTableIsSync)
            {
                var value = BaseLibrary.ClassLibrary.DataConver.ToBool(e.Value);
                var datatable = tDataTableBindingSource.Current as DAL.DB.Tables.TDataTable;
                if (datatable == null) return;
                if (datatable.IsSync == value) return;
                datatable.IsSync = value;
                var project = tProjectBindingSource.Current as DAL.DB.Tables.TProject;
                if (project == null) return;
                {
                    try
                    {
                        var syncDataTable = MDL.CPublic.dc.TDataTable.FirstOrDefault(c => c.ProjectID == project.ID && c.TableName == datatable.TableName);
                        if (datatable.IsSync)
                        {
                            if (syncDataTable == null)
                                syncDataTable = new DAL.DB.Tables.TDataTable() { ProjectID = project.ID, TableName = datatable.TableName };
                            project.sync.checkSyncTable(datatable.TableName);
                        }
                        else
                        {
                            if (syncDataTable != null)
                                syncDataTable.Delete();
                            project.sync.cancelSyncTable(datatable.TableName);
                        }
                        MDL.CPublic.dc.Save(syncDataTable);
                        
                        
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        private void repositoryItemButtonEdit_Project_Operator_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var project = tProjectBindingSource.Current as DAL.DB.Tables.TProject;
            if (project == null) return;
            switch (e.Button.Caption)
            {
                case "初始化":
                    project.sync.CreateMaster();
                    break;
                case "取消":
                    project.sync.CancelMaster();
                    break;
            }
        }

        private void repositoryItemButtonEdit_DataBaseOperator_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var project = tProjectBindingSource.Current as DAL.DB.Tables.TProject;
            if (project == null) return;
            var database = tDataBaseBindingSource.Current as DAL.DB.Tables.TDataBase;
            switch (e.Button.Caption)
            {
                case "删除":
                    if (MessageBox.Show(string.Format("确定要删除同步库{0}吗?", database.DataBase), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        database.Delete();
                        MDL.CPublic.dc.Save(database);
                        project.sync.ReStart();
                        tDataBaseBindingSource.Remove(database);
                    }
                    break;
            }
        }
    }
}
